package com.kabigon.tiny.pojo.response;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 分页数据
 * @author xu.biao
 * @version v1.0
 * @Package com.kabigon.tiny.pojo.response
 * @data 2022/5/16 1:09
 */
@Data
public class QueryData<T> {

    /**
     * 数据列表
     */
    private List<T> data;
    /**
     * 总记录数
     */
    private long total;
    /**
     * 当前页，从1开始
     */
    private long pageNo;
    /**
     * 分页大小
     */
    private long pageSize;

    public QueryData() {

    }

    public QueryData(IPage<T> page) {

        this.setData(page.getRecords());
        this.setPageNo(page.getCurrent());
        this.setPageSize(page.getSize());
        this.setTotal(page.getTotal());
    }

    public <E> QueryData(IPage<E> page, Function<E, T> mapper) {

        this.setPageNo(page.getCurrent());
        this.setPageSize(page.getSize());
        this.setTotal(page.getTotal());

        if (CollUtil.isEmpty(page.getRecords())) {
            this.setData(Collections.emptyList());
        } else {
            this.setData(page.getRecords().stream().map(mapper).collect(Collectors.toList()));
        }

    }

    public QueryData(List<T> records, long total, int pageNo, int pageSize) {
        this.data = records;
        this.total = total;
        this.pageNo = pageNo;
        this.pageSize = pageSize;
    }

    public <E> QueryData(IPage<E> page, List<T> records) {
        this.data = records;
        this.setPageNo(page.getCurrent());
        this.setPageSize(page.getSize());
        this.setTotal(page.getTotal());
    }
}
